//
//  OBWebViewController.m
//  onebuycheckstand
//
//  Created by xu yao on 2021/3/2.
//

#import "UWebViewController.h"
#import <WebKit/WebKit.h>
#import "AppConfig.h"
#import "UPayResult.h"
#import "UPaySDK.h"
#import "UPayReq.h"
#import "UGZRCpayModel.h"
#import "EnvironmentDefine.h"
@interface UWebViewController () <WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) WKWebView* wkWebview;

@end

@implementation UWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    self.navigationItem.title = @"支付";
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    if (@available(iOS 13.0, *)) {
//        NSBundle*bundle = [NSBundle bundleForClass:[self class]];
//        [backButton setImage:[UIImage imageNamed:[UIImage imageNamed:@"UPaySDK.bundle/closed"] inBundle:bundle withConfiguration:nil] forState:UIControlStateNormal];
//    } else {
//        // Fallback on earlier versions
//    }
    [backButton setTitle:@"x  " forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont systemFontOfSize:40];
    backButton.frame = CGRectMake(0, 0, 44, 44);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [backButton addTarget:self action:@selector(onClose) forControlEvents:UIControlEventTouchUpInside];
    
    // 初始化webview
    [self initWebView];
    // 注册js方法
    [self initJsMethod];
}

- (void)onClose {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定取消支付" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [UPaySDK closecheckstand];
    }];
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:yesAction];
    [alertController addAction:noAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
        NSLog(@"clicked navigationbar back button");
    }
}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    //禁用右滑返回
//    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//}
//
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    //恢复右滑返回
//    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
//}

- (void)initJsMethod {
    [self.wkWebview.configuration.userContentController addScriptMessageHandler:self name:USDK_WEBKIT_ACTION_PAY];
    [self.wkWebview.configuration.userContentController addScriptMessageHandler:self name:USDK_WEBKIT_PAY_RESULT];
    [self.wkWebview.configuration.userContentController addScriptMessageHandler:self name:USDK_WEBKIT_CLOSE_WINDOWS];
}

- (void)initWebView {
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    [configuration setValue:@YES forKey:@"_allowUniversalAccessFromFileURLs"];//允许跨域
    [configuration.preferences setValue:@"TRUE" forKey:@"allowFileAccessFromFileURLs"];//允许加载沙盒路径
    configuration.preferences = [WKPreferences new];
    configuration.preferences.minimumFontSize = 10;
    configuration.preferences.javaScriptEnabled = YES;
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    WKUserContentController *userController = [WKUserContentController new];
    NSString *js = @" $('meta[name=description]').remove(); $('head').append( '' );";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择

    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [userController addUserScript:script];
    [userController addUserScript:noneSelectScript];
    configuration.userContentController = userController;
    [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
    if (@available(iOS 10.0, *)) {
         [configuration setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
    }
    WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height) configuration:configuration];
    webview.navigationDelegate = self;
    webview.UIDelegate = self;
    webview.scrollView.scrollEnabled = NO;
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.stageSessionURL]]];
    [self.view addSubview:webview];
    webview.backgroundColor = [UIColor whiteColor];
    self.wkWebview = webview;
    
    // 设置UA
    [webview evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSString *userAgent = result;
        NSString *newUserAgent = [userAgent stringByAppendingFormat:@"/%@", CUSTOM_USER_AGENT];
        [self.wkWebview setCustomUserAgent:newUserAgent];
    }];
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    NSURL *URL = navigationAction.request.URL;
//    NSString *scheme = [URL scheme];
//    if ([URL.absoluteString containsString:@"https://uppweb.gogbuy.com"]) {
//        [[UIApplication sharedApplication] openURL:URL];
//        NSLog(@"%@",URL.absoluteString);
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;
//    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:USDK_WEBKIT_ACTION_PAY]) {
        //支付的内容
        UPayResult *result = [UPayResult setpayResult:message.body];
        LCLog(@"%@",message.body);
        if ([result.payChannel isEqualToString:@"WXAPP"]) {
            if (!result.param) {
                LCLog(@"订单的签名不能为空");
                return;
            }
//                NSData *jsonData = [result.orderData dataUsingEncoding:NSUTF8StringEncoding];
//                    NSError *err;
            NSDictionary *dic = result.param;
//                [NSJSONSerialization JSONObjectWithData:jsonData
//                                                                        options:NSJSONReadingMutableContainers
//                                                                          error:&err];
            UPayReq *request = [[UPayReq alloc] init];
            request.partnerId = dic[@"partnerid"];
            request.prepayId = dic[@"prepayid"];
            request.package = dic[@"package"];
            request.nonceStr = dic[@"noncestr"];

            NSString *timestamp = dic[@"timestamp"];
            request.timeStamp = [timestamp intValue];
            request.sign = dic[@"sign"];
            [UPaySDK wechatPay:request];
        } else if ([result.payChannel isEqualToString:@"ALIPAYAPP"]) {
            [UPaySDK alipay:result.param];
        } else if ([result.payChannel isEqualToString:@"GRCBAPP"]) {
            UGZRCpayModel *payModel = [[UGZRCpayModel alloc] init];
            payModel.AppNo = result.param[@"AppNo"];
            payModel.MainOrderNo = result.param[@"MainOrderNo"];
            payModel.MerNo = result.param[@"MerNo"];
            payModel.Sign = result.param[@"Sign"];
            payModel.SignType = result.param[@"SignType"];
            payModel.Token = result.param[@"Token"];
            payModel.Ext = @"UPaySDK支付";
            [UPaySDK GZRCpay:payModel];
        }
    } else if ([message.name isEqualToString:USDK_WEBKIT_PAY_RESULT]) {
        //H5支付的结果
         
    } else if ([message.name isEqualToString:USDK_WEBKIT_CLOSE_WINDOWS]) {
        
    }
}


// 加载完毕
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
}

#pragma 向h5发送消息
- (void)getPermissions:(id)permission type:(NSString *)type{
    NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
    dic[@"data"] = permission;
    dic[@"type"] = type;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSString *jsStr = [NSString stringWithFormat:@"postMessage(%@, '*')", jsonStr];
    [self.wkWebview evaluateJavaScript:jsStr completionHandler:^(id _Nonnull result, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

@end
